﻿using HK.Core.Serializable.Attribute;
using HK.Core.Utils;
using HK.Editor.Serializable.Protocol.Drawer;
using UnityEditor;
using UnityEngine;

namespace HK.Editor.Serializable.Drawer
{
    /// <summary>
    /// Drawer - 日期
    /// </summary>
    [CustomPropertyDrawer(typeof(DateTimeAttribute))]
    public class DateTimeDrawer : GUIPropertyDrawer<DateTimeAttribute>, IDateTimeDrawer
    {
        /// <summary>
        /// 日期格式
        /// </summary>
        public UtilsTime.DateFormat Format => SelfAttr?.Format ?? UtilsTime.DateFormat.YyyyMmDdHhMmSs;

        private long lastTimeTicks = -1L;
        private string _displayDateTime = null;

        /// <summary>
        /// 显示日志
        /// </summary>
        public string DisplayDateTime
        {
            get
            {

                var curTimeTicks = SelfProperty?.longValue ?? -1L;
                if (lastTimeTicks != curTimeTicks)
                {
                    _displayDateTime = null;
                }
                
                if (!string.IsNullOrEmpty(_displayDateTime)) return _displayDateTime;

                var dateTimeTicks = SelfProperty?.longValue ?? 0L;
                _displayDateTime = 0 >= dateTimeTicks ? "Invalid DateTime" : UtilsTime.ConvertByFormat(dateTimeTicks, Format);
                
                lastTimeTicks = curTimeTicks;
                return _displayDateTime;
            }
        }

        private GUIContent _displayContent = null;
        public GUIContent DisplayContent
        {
            get
            {
                if (null != _displayContent)
                {
                    _displayContent.text = DisplayDateTime;
                    return _displayContent;
                }
                _displayContent = new GUIContent(DisplayDateTime);
                return _displayContent;
            }
        }

#region Draw

#region Caption
        
        /// <summary>
        /// 绘制标题
        /// </summary>
        /// <param name="iRect">绘制矩形区域</param>
        /// <param name="iEvent">Event</param>
        /// <param name="iCaption">标题</param>
        /// <returns>绘制的矩形区域</returns>
        protected override Rect DrawCaption(Rect iRect, Event iEvent, GUIContent iCaption)
        {
            var displayRect = iRect;

            var titleRect = displayRect;
            titleRect.xMin += LabelIntent;
            titleRect.xMax -= HorizontalSpacing;
            titleRect.y -= 1;
            EditorGUI.LabelField(titleRect, iCaption, DisplayContent);
            
            return displayRect;
        }

#endregion

#endregion
        
    }
}
